package com.cxq;

/**
 * Created by cxq on 2020/7/26.
 */
public class ThreadLocalDemo {
    //创建银行对象：栈，取款、存款
    static class Bank {
        private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
            @Override
            protected Integer initialValue() {
                return 0;
            }
        };

        public Integer get() {
            return threadLocal.get();
        }


        public void set(Integer money) {
            threadLocal.set(threadLocal.get() + money);
        }

    }

    //创建转账对象，在银行中取钱、转账、保存到账户
    static class Transfer implements Runnable {
        Bank bank = new Bank();

        public Transfer(Bank bank) {
            this.bank = bank;
        }

        public void run() {
            for (int i = 0; i < 10; i++) {
                bank.set(10);
                System.out.println(Thread.currentThread().getName()+"账户余额："+bank.get());
            }
        }
    }
    //在main方法中使用两个对象模拟转账

    public static void main(String[] args) {
        Bank bank = new Bank();
        Transfer transfer = new Transfer(bank);
        Thread thread1 = new Thread(transfer,"用户1");
        Thread thread2 = new Thread(transfer,"用户2");
        thread1.start();
        thread2.start();
    }
}
